package com.example.redisdemo.websocket;

import com.example.redisdemo.entity.SubMessage;
import com.example.redisdemo.util.RedisOperatingUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDate;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jackcooper
 * @create 2017-12-28 13:04
 */
@ServerEndpoint(value = "/websocket")
@Component
public class ApplicationWebSocket {
    //静态变量，用来记录当前在线连接数。设计成线程安全的。
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    private RedisOperatingUtil redisOperatingUtil;

    //concurrent包的线程安全Set，用来存放每个客户端对应的ApplicationWebSocket对象。
    private static CopyOnWriteArraySet<ApplicationWebSocket> webSocketSet = new CopyOnWriteArraySet<ApplicationWebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // 解决redis操作工具类注入为null的问题
    public static ApplicationWebSocket webSocketServer;

    @PostConstruct
    public void init() {
        webSocketServer = this;
        webSocketServer.redisOperatingUtil = this.redisOperatingUtil;
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            sendMessage("当前在线人数为：" + getOnlineCount());
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, JSONException {
        // 客户端发送的消息
        JSONObject jsReply = new JSONObject(message);
        // 添加在线人数
        jsReply.put("onlineUsers", getOnlineCount());
        if (jsReply.has("buddyId")) {
            // 获取推送方id
            String userId = jsReply.getString("userID");
            // 获取被推送方id
            String buddyId = jsReply.getString("buddyId");
            // 非测试数据则推送消息
            if (!buddyId.equals("121710f399b84322bdecc238199d6888")) {
                // 发送消息至推送方
                sendInfo(jsReply.toString(), userId);
            }
            // 构造聊天记录实体类数据
            SubMessage subMessage = new SubMessage();
            subMessage.setAvatarSrc(jsReply.getString("avatarSrc"));
            subMessage.setUserId(jsReply.getString("userID"));
            subMessage.setUserName(jsReply.getString("username"));
            subMessage.setMsgText(jsReply.getString("msg"));
            subMessage.setMsgId(jsReply.getString("msgId"));
            subMessage.setCreateTime(LocalDate.now().toString());
            subMessage.setStatus(false);
            // 将聊天记录对象保存到redis中
            webSocketServer.redisOperatingUtil.listRightPush("subMessage", subMessage);
            // 发送消息至被推送方
            sendInfo(jsReply.toString(), buddyId);
        }
    }

    /**
     * 发生错误时调用
     *
     * @OnError
     */
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        //getBasicRemote是阻塞式的
        this.session.getBasicRemote().sendText(message);
        //非阻塞式的
        // this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, String userId) throws IOException {
        for (ApplicationWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount.get();
    }

    public static synchronized void addOnlineCount() {
        ApplicationWebSocket.onlineCount.getAndIncrement();
    }

    public static synchronized void subOnlineCount() {
        ApplicationWebSocket.onlineCount.getAndDecrement();
    }
}